<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" width="80%" :min-height="500" @ok="handleSubmit">
      <BasicForm @register="registerForm"/>
      <div style="margin-bottom: 30px"></div>
      <BizPurchaseRequisitionDetailList v-if="reqId" :req-id="reqId" />
    <template #appendFooter>
      <a-button type="primary" :disabled="applyDisable" @click="sendApply">审批</a-button>
    </template>
    <GateWayModal @register="registerGwModal" @success="handleGwSuccess" />
  </BasicModal>
</template>

<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import {BasicModal, useModal, useModalInner} from '/@/components/Modal';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../BizPurchaseRequisition.data';
    import {saveOrUpdate} from '../BizPurchaseRequisition.api';
    import BizPurchaseRequisitionDetailList from "@/views/business/purchase/biz_purchase_requisition_detail/BizPurchaseRequisitionDetailList.vue";
    import { usePermission } from '/@/hooks/web/usePermission';
    import {useMessage} from "@/hooks/web/useMessage";
    import GateWayModal from '/@/components/ApplyModal/GateWay.vue'
    import {getProcessDataList} from "@/views/activiti/modules/ActReModel.api";
    import {isArray} from "@/utils/is";

    const { hasPermission } = usePermission();
    const {createMessage} = useMessage()
    const [registerGwModal, {openModal}] = useModal();
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const reqId = ref(null)

    const applyDisable = ref(true)
    const applyKeyArr = ref([])
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 12}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter,okText:'保存',cancelText:'关闭'});
        isUpdate.value = !!data?.isUpdate;
        reqId.value = null

        applyKeyArr.value = data.applyKeyArr
        dealApplyBtnStat(data.record)

        if (unref(isUpdate)) {
           reqId.value = data.record.id
            //表单赋值
            await setFieldsValue({
                ...data.record,
            });
        }
        // 隐藏底部时禁用整个表单
       setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            setModalProps({confirmLoading: true});
            //提交表单
            reqId.value = await saveOrUpdate(values, isUpdate.value);
            await setFieldsValue({id:reqId.value })
            isUpdate.value = true
            applyDisable.value=false
            //关闭弹窗
            //closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }

    function dealApplyBtnStat(record){
      if (!record){
        applyDisable.value=true
        return
      }
      applyDisable.value = !([0,3].includes(record.status)&&hasPermission(applyKeyArr.value))
    }

    async function findApplyFlow(applyKey){
      const result = await getProcessDataList({ status: 1, roles: true })
      if (isArray(result)){
        return result.find(flow=>flow.processKey==applyKey)
      }
      return null
    }

    async function sendApply(){
      let values = await validate();
      setModalProps({confirmLoading: true});
      //提交表单
      reqId.value = await saveOrUpdate(values, isUpdate.value);
      await setFieldsValue({id:reqId.value })
      isUpdate.value = true
      const applyKey = applyKeyArr.value.length?applyKeyArr.value[0]:null
      if (!applyKey){
        createMessage.error("未知流程!")
        return
      }
      const flow = await findApplyFlow(applyKey)
      if (!flow){
        createMessage.error("流程未定义!")
        return
      }
      const formdata = {
        title:values.name,
        procDefId: flow?.id,
        procDeTitle: flow?.name,
        processKey:flow?.processKey,
        tableName: flow?.businessTable,
        name: flow?.name,
        tableId: reqId.value
      }
      openModal(true,{
        record:formdata
      })

    }

    function handleGwSuccess(){
      closeModal()
      emit('success');

    }

</script>

<style lang="less" scoped>
	/** 时间和数字输入框样式 */
  :deep(.ant-input-number){
		width: 100%
	}

	:deep(.ant-calendar-picker){
		width: 100%
	}
</style>
